var MixlyStatusBar = {};

MixlyStatusBar.selected = false;

MixlyStatusBar.ace = null;

MixlyStatusBar.portAce = {};

MixlyStatusBar.portName = [];

/**
* @function 初始化状态栏
* @description 初始化状态栏
* @return void
*/
MixlyStatusBar.init = function () {
    MixlyStatusBar.ace = ace.edit("div_inout_middle");
    MixlyStatusBar.ace.setOption("theme", "ace/theme/xcode");
    MixlyStatusBar.ace.getSession().setMode("ace/mode/python");
    MixlyStatusBar.ace.setFontSize(document.body.clientWidth / 95);
    MixlyStatusBar.ace.setReadOnly(false);
    MixlyStatusBar.ace.setScrollSpeed(0.3);
    MixlyStatusBar.ace.setShowPrintMargin(false);
    MixlyStatusBar.ace.renderer.setShowGutter(false);
    MixlyStatusBar.ace.commands.addCommands([
        {
            name: "increaseFontSize",
            bindKey: "Ctrl-=|Ctrl-+",
            exec: function (editor) {
                var size = parseInt(editor.getFontSize(), 10) || 12;
                editor.setFontSize(size + 1);
            }
        }, {
            name: "decreaseFontSize",
            bindKey: "Ctrl+-|Ctrl-_",
            exec: function (editor) {
                var size = parseInt(editor.getFontSize(), 10) || 12;
                editor.setFontSize(Math.max(size - 1 || 1));
            }
        }, {
            name: "resetFontSize",
            bindKey: "Ctrl+0|Ctrl-Numpad0",
            exec: function (editor) {
                editor.setFontSize(12);
            }
        }, {
            name: "sendCtrlC",
            bindKey: "Ctrl-Shift-C",
            exec: function (editor) {
                if (MixlyEnv.isClient) {
                    MixlySerial.writeCtrlC();
                } else {
                    MixlyWebSerial.writeCtrlC();
                }
            }
        }, {
            name: "sendCtrlD",
            bindKey: "Ctrl-Shift-D",
            exec: function (editor) {
                if (MixlyEnv.isClient) {
                    MixlySerial.writeCtrlD();
                } else {
                    MixlyWebSerial.writeCtrlD();
                }
            }
        }, {
            name: "Empty",
            bindKey: "Ctrl-E",
            exec: function (editor) {
                MixlyStatusBar.setValue("");
            }
        }
    ]);
}

/**
* @function 显示、隐藏或反转状态栏
* @description 显示、隐藏或反转状态栏
* @param type {number} 0 - 反转状态栏，1 - 打开状态栏，2 - 关闭状态栏
* @return void
*/
MixlyStatusBar.show = function (type) {
    var oBox = getid("table_whole");
    var content_blocks = getid("content_blocks");
    var content_arduino = getid("content_arduino");
    var content_xml = getid("content_xml");
    var content_area = getid("content_area");
    var side_code_parent = getid("side_code_parent");
    var td_top = getid("td_top");
    var td_middle = getid("td_middle");
    if (type != 2 && type != 0 && MixlyStatusBar.selected) return;
    if (MixlyStatusBar.selected || type == 2) {
        //td_top.style.display = 'none';
        td_middle.style.display = 'none';
        //td_top.style.height = '0px';
        td_middle.style.height = '0px';
        content_blocks.style.height = "100%";
        content_arduino.style.height = "100%";
        content_xml.style.height = "100%";
        content_area.style.height = "100%";
        side_code_parent.style.height = "100%";
        MixlyStatusBar.selected = false;
    } else {
        td_top.style.display = '';
        td_middle.style.display = '';
        td_top.style.height = '3px';
        td_middle.style.height = 'auto';
        var iT = 0.8;
        var percent = oBox.clientHeight * iT;
        content_blocks.style.height = percent + "px";
        content_arduino.style.height = percent + "px";
        content_area.style.height = percent + "px";
        side_code_parent.style.height = percent + "px";
        mid_td.style.height = percent + "px";
        td_middle.style.height = "auto";
        MixlyStatusBar.selected = true;
    }
    editor.resize();
    Blockly.fireUiEvent(window, 'resize');
}

/**
* @function 状态栏显示数据
* @description 显示数据到状态栏内
* @param data {String} 需要显示的字符串
* @param scroll {Boolean} 是否将滚动条移到底部，true - 移动到底部，false - 保持当前位置不变
* @return void
*/
MixlyStatusBar.setValue = function (data, scroll = false) {
    if (!MixlyStatusBar.ace) return;
    if (MixlyStatusBar.getValue() == data) return;
    MixlyStatusBar.ace.setValue(data);
    if (scroll)
        MixlyStatusBar.ace.gotoLine(MixlyStatusBar.ace.session.getLength());
}

/**
* @function 获取状态栏数据
* @description 获取当前状态栏显示的数据
* @return String
*/
MixlyStatusBar.getValue = function () {
    if (!MixlyStatusBar.ace) return "";
    return MixlyStatusBar.ace.getValue();
}

/**
* @function 状态栏追加数据
* @description 显示数据到状态栏内
* @param data {String} 需要追加的字符串
* @param scroll {Boolean} 是否将滚动条移到底部，true - 移动到底部，false - 保持当前位置不变
* @return void
*/
MixlyStatusBar.addValue = function (data, scroll = false) {
    if (!MixlyStatusBar.ace) return;
    MixlyStatusBar.setValue(MixlyStatusBar.getValue() + data, scroll);
    MixlyStatusBar.ace.resize();
}

/**
* @function 移动滚动条到底部
* @description 移动状态栏的滚动条到最底部
* @return void
*/
MixlyStatusBar.scrollToTheBottom = function () {
    if (!MixlyStatusBar.ace) return;
    MixlyStatusBar.ace.gotoLine(MixlyStatusBar.ace.session.getLength());
}

/**
* @function 移动滚动条到顶部
* @description 移动状态栏的滚动条到最顶部
* @return void
*/
MixlyStatusBar.scrollToTheTop = function () {
    if (!MixlyStatusBar.ace) return;
    MixlyStatusBar.ace.gotoLine(0);
}

MixlyStatusBar.tabAdd = function (portName) {
    if (!MixlyStatusBar.portName.includes(portName)) {
        layui.use('element', function () {
            let element = layui.element;
            let contentData = `<pre class="tab-ace" id="tab-${portName}-ace" align="center"></pre>`;
            element.tabAdd('status-bar-ace', {
                title: portName + `<span id="tab-ace-${portName}-span" class="layui-badge-dot layui-bg-orange"></span>`,
                content: contentData,
                id: `tab-ace-${portName}`
            });
            MixlyStatusBar.portName.push(portName);
            MixlyStatusBar.portAce[portName] = ace.edit(`tab-${portName}-ace`);
            if (window?.localStorage?.Theme === "Dark") {
                MixlyStatusBar.portAce[portName].setOption("theme", "ace/theme/terminal");
            } else {
                MixlyStatusBar.portAce[portName].setOption("theme", "ace/theme/xcode");
            }
            MixlyStatusBar.portAce[portName].getSession().setMode("ace/mode/python");
            MixlyStatusBar.portAce[portName].setFontSize(document.body.clientWidth / 95);
            MixlyStatusBar.portAce[portName].setReadOnly(false);
            MixlyStatusBar.portAce[portName].setScrollSpeed(0.3);
            MixlyStatusBar.portAce[portName].setShowPrintMargin(false);
            MixlyStatusBar.portAce[portName].renderer.setShowGutter(false);
            MixlyStatusBar.portAce[portName].commands.addCommands([
                {
                    name: "increaseFontSize",
                    bindKey: "Ctrl-=|Ctrl-+",
                    exec: function (editor) {
                        var size = parseInt(editor.getFontSize(), 10) || 12;
                        editor.setFontSize(size + 1);
                    }
                }, {
                    name: "decreaseFontSize",
                    bindKey: "Ctrl+-|Ctrl-_",
                    exec: function (editor) {
                        var size = parseInt(editor.getFontSize(), 10) || 12;
                        editor.setFontSize(Math.max(size - 1 || 1));
                    }
                }, {
                    name: "resetFontSize",
                    bindKey: "Ctrl+0|Ctrl-Numpad0",
                    exec: function (editor) {
                        editor.setFontSize(12);
                    }
                }, {
                    name: "Empty",
                    bindKey: "Ctrl-E",
                    exec: function (editor) {
                        MixlyStatusBarPort.setValue(portName, "");
                    }
                }
            ]);

            element.on('tabDelete(status-bar-ace)', function (data) {
                let portName = MixlyStatusBar.portName[data.index - 1];
                MixlyStatusBar.portAce[portName].destroy();
                MixlyStatusBar.portAce[portName].container.remove();
                MixlyStatusBar.portName.splice(data.index - 1, 1);
                delete MixlyStatusBar.portAce[portName];
                if (MixlySerial.object && MixlySerial.object.isOpen && MixlySerial.object.path == portName) {
                    MixlySerial.object.close();
                    MixlyStatusBar.taChange("output");
                    if (MixlyStatusBar.getValue().lastIndexOf("\n") != MixlyStatusBar.getValue().length - 1) {
                        MixlyStatusBar.addValue('\n' + indexText['已关闭串口'] + portName + '\n', true);
                    } else {
                        MixlyStatusBar.addValue(indexText['已关闭串口'] + portName + '\n', true);
                    }
                }
            });

            element.on('tab(status-bar-ace)', function (data) {
                if (data.index == 0) {
                    MixlyStatusBar.scrollToTheBottom();
                } else {
                    MixlyStatusBarPort.scrollToTheBottom(MixlyStatusBar.portName[data.index - 1]);
                }
            });
        });
    } else {
        MixlyStatusBarPort.open(portName);
    }
}

MixlyStatusBar.taChange = function (id) {
    layui.use('element', function () {
        let element = layui.element;
        element.tabChange("status-bar-ace", `tab-ace-${id}`);
    });
}

MixlyStatusBar.init();

var MixlyStatusBarPort = {};

/**
* @function 状态栏显示数据
* @description 显示数据到状态栏内
* @param data {String} 需要显示的字符串
* @param scroll {Boolean} 是否将滚动条移到底部，true - 移动到底部，false - 保持当前位置不变
* @return void
*/
MixlyStatusBarPort.setValue = function (portName, data, scroll = false) {
    if (!MixlyStatusBar.portAce[portName]) return;
    if (MixlyStatusBarPort.getValue(portName) == data) return;
    MixlyStatusBar.portAce[portName].setValue(data);
    if (scroll)
        MixlyStatusBar.portAce[portName].gotoLine(MixlyStatusBar.portAce[portName].session.getLength());
}

/**
* @function 获取状态栏数据
* @description 获取当前状态栏显示的数据
* @return String
*/
MixlyStatusBarPort.getValue = function (portName) {
    if (!MixlyStatusBar.portAce[portName]) return "";
    return MixlyStatusBar.portAce[portName].getValue();
}

/**
* @function 状态栏追加数据
* @description 显示数据到状态栏内
* @param data {String} 需要追加的字符串
* @param scroll {Boolean} 是否将滚动条移到底部，true - 移动到底部，false - 保持当前位置不变
* @return void
*/
MixlyStatusBarPort.addValue = function (portName, data, scroll = false) {
    if (!MixlyStatusBar.portAce[portName]) return;
    MixlyStatusBarPort.setValue(portName, MixlyStatusBarPort.getValue(portName) + data, scroll);
}

/**
* @function 移动滚动条到底部
* @description 移动状态栏的滚动条到最底部
* @return void
*/
MixlyStatusBarPort.scrollToTheBottom = function (portName) {
    if (!MixlyStatusBar.portAce[portName]) return;
    MixlyStatusBar.portAce[portName].gotoLine(MixlyStatusBar.portAce[portName].session.getLength());
}

/**
* @function 移动滚动条到顶部
* @description 移动状态栏的滚动条到最顶部
* @return void
*/
MixlyStatusBarPort.scrollToTheTop = function (portName) {
    if (!MixlyStatusBar.portAce[portName]) return;
    MixlyStatusBar.portAce[portName].gotoLine(0);
}

MixlyStatusBarPort.open = function (portName) {
    if (document.getElementById(`tab-ace-${portName}-span`)) {
        let aceSpan = document.getElementById(`tab-ace-${portName}-span`);
        aceSpan.className = "layui-badge-dot layui-bg-orange";
    }
}

MixlyStatusBarPort.close = function (portName) {
    if (document.getElementById(`tab-ace-${portName}-span`)) {
        let aceSpan = document.getElementById(`tab-ace-${portName}-span`);
        aceSpan.className = "layui-badge-dot layui-bg-blue";
    }
}